package com.rgs.se.data.queue;

import lombok.NoArgsConstructor;

import java.net.Inet4Address;

/**
 * @author Ren Gaoshuai
 * @ClassName ListQueue
 * @date 2022-04-07 21:57
 **/
public class ListQueue<E> implements MyQueue<E> {

    private class Node{
        public E data;
        public Node next;
        public Node(E e, Node next) {
            this.data = e;
            this.next = next;
        }

        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }

    }
    private Node head,tail;
    private int size;

    public ListQueue(){
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public void enQueue(E e) {
        Node node = new Node(e);
        if (tail == null){
            //第一次添加
           tail = node;
           head = tail;
        }else{
           tail.next = node;
           tail = tail.next;
        }
        size++;

    }

    @Override
    public E deQueue() {
        if (isEmpty()){
            throw new IllegalArgumentException("队列空！");
        }
        Node delNode = head;
        if (tail == head){
            head = null;
            tail = null;

        }else{
            head = head.next;
            delNode.next = null;
        }
        size--;
        return delNode.data;
    }

    @Override
    public E getFront() {
        if (isEmpty()){
            throw new IllegalArgumentException("队列空！");
        }
        return head.data;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString(){
        StringBuilder builder = new StringBuilder();
        builder.append("Queue:front ");
        Node cur = head;
        while(cur != null){
            builder.append(cur.data + "->");
            cur= cur.next;
        }
        builder.append("NULL tail");
        return builder.toString();
    }


    public static void main(String[] args) {
        ListQueue<Integer> queue = new ListQueue<>();
        for (int i = 0; i < 5; i++) {
            queue.enQueue(i);
            System.out.println(queue);
        }
        queue.deQueue();
        System.out.println(queue);
    }
}
